// tslint:disable
import { Component, OnInit, Input, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { HttpService } from 'src/app/shared/service/http.service';
import { AppSpinAnchorDirective } from 'src/app/route/entry/spin-anchor.directive';
import { EventService } from 'src/app/shared/service/event.service';


@Component({
  selector: 'app-spin',
  templateUrl: './spin.component.html',
  styleUrls: ['./spin.component.scss'],
})
export class SpinComponent implements OnInit {
  @Input() tagData: any;
  @ViewChild(AppSpinAnchorDirective) appSpinAnchor: AppSpinAnchorDirective;
  isSpinning = true;
  show = true;
  coms: any;
  currentDataArray = [];
  constructor(
    private http: HttpService,
    private eventService: EventService,
    private componentFactoryResolver: ComponentFactoryResolver,
  ) {
    console.log('entry spinComponent...');
  }

  ngOnInit() {
    this.eventService.eventEmit.on("getPageData" + this.tagData.data.tagOrder, pageData => {
      const coms = pageData.coms;
      this.loadComponent(coms);
    });
    this.getPage();
  }
  async getPage() {
    // 发送请求
    if (this.tagData.data.params.search) {
      this.tagData.data.params.search = this.tagData.data.params.search.replace(/^\"|\"$/g, '').replace(/[\\]/g, "");
    }
    await this.http.post('application/loadTag', this.tagData.data, res => {
      if (JSON.parse(res.script).type === 'error') {
        this.isSpinning = false;
      } else {
        if (JSON.parse(res.script).type === 'tag') {
          const asyncTagData = JSON.parse(res.script);
          this.show = false;
          if (asyncTagData.style === 'tag.PhoneTagLogic') {
            localStorage.setItem("asyncGetPhoneNumberTag", JSON.stringify(asyncTagData.data));
            this.eventService.eventEmit.emit("asyncGetPhoneNumber", "");
          } else {
            res['tagOrder'] = this.tagData.data.tagOrder;
            this.eventService.eventEmit.emit("sendPageData", res);

          }
        }
      }
    }, () => {
      this.isSpinning = false;
    });

  }
  loadComponent(coms) {
    this.currentDataArray = [];
    // this.appSpinAnchor.viewContainerRef.clear();
    // console.log('coms tag ===' + coms);
    coms.forEach((v) => {
      // console.log('v === ' + JSON.stringify(v));
      this.currentDataArray.push(v.tagData);
      // const componentFactory = this.componentFactoryResolver.resolveComponentFactory(v.component);
      // const viewContainerRef = this.appSpinAnchor.viewContainerRef;
      // const componentRef = viewContainerRef.createComponent(componentFactory);
      // componentRef.instance['tagData'] = v.tagData;
    });
  }
  ngOnDestroy(): void {
    this.eventService.eventEmit.removeListener('getPageData' + this.tagData.data.tagOrder);
  }
}
